package framework;

/**
 * This is a generic factory class (and my attempt at producing reusable
 * code). This is a reusable factory class that has the functionality of
 * creating new classes. It uses Java reflection to instantiate new objects.
 * 
 * @author Michael Deng
 * 
 * @param <T> Abstract handler for all new classes created
 */
public class Factory<T> {

    private String myPackagePath = "";

    /**
     * The constructor creates the new Map that holds newly created classes.
     * 
     * @param packagePath path to the package containing the classes
     */
    public Factory (String packagePath) {
        myPackagePath = packagePath + ".";
    }

    /**
     * creates a new class according to the string given; if it does not
     * exist in the class map.
     * 
     * @param className name of the class to create
     * @return
     */
    @SuppressWarnings("unchecked")
    public T createObject (String className) {
        String fullClassPath = null;
        T newAction = null;

        try {
            fullClassPath = myPackagePath + className;
            newAction = (T) Class.forName(fullClassPath).newInstance();
        }
        catch (InstantiationException e) {
            return null;
        }
        catch (IllegalAccessException e) {
            return null;
        }
        catch (ClassNotFoundException e) {
            return null;
        }
        catch (IllegalArgumentException e) {
            return null;
        }
        catch (SecurityException e) {
            return null;
        }
        return newAction;
    }
}
